const app = getApp();
const fs = wx.getFileSystemManager()
import {
  getPrintFileInfo,
  saveOrUpdatePrint,
  getQueueList,
  deleteQueueById,
  getTotalFeeByService,
  createPrintOrder,
  queryPayResult,
  getDeliveryRange
} from "../../common/api";

Page({
  data: {
    hideSetting: true,
    hideAdd: true,
    hideDelivery: true,
    deliveryType: -1, // 配送方式
    pagesPicker: [
      [1, 2, 3, 4, 5],
      [1, 2, 3, 4, 5]
    ],
    pickUpArray: [],
    deliveryArray: [{
      id: '999',
      name: '现场自取'
    }, {
      id: '001',
      name: '送货上门'
    }, {
      id: '002',
      name: '代取点自取'
    }],
    deliveryAddress: "请选择送货方式",
    deliveryContact: "",
    deliveryPhone: "",
    ext: {
      jpeg: {
        icon: "../../images/JPG@2x.png",
        color: "#6CE4D8"
      },
      jpg: {
        icon: "../../images/JPG@2x.png",
        color: "#6CE4D8"
      },
      png: {
        icon: "../../images/PNG@2x.png",
        color: "#FFD93B"
      },
      xls: {
        icon: "../../images/XLSX@2x.png",
        color: "#9ED463"
      },
      xlsx: {
        icon: "../../images/XLSX@2x.png",
        color: "#9ED463"
      },
      ppt: {
        icon: "../../images/PPT@2x.png",
        color: "#F8A53B"
      },
      pptx: {
        icon: "../../images/PPT@2x.png",
        color: "#F8A53B"
      },
      pdf: {
        icon: "../../images/PDF@2x.png",
        color: "#EF427C"
      },
      doc: {
        icon: "../../images/DOC@2x.png",
        color: "#5E7EE8"
      },
      docx: {
        icon: "../../images/DOC@2x.png",
        color: "#5E7EE8"
      }
    },
    printer_name: "未选择打印机",

    hideSides: false,
    hideColor: false,
    hideOrientation: false,
    hidePages: false,
    hideCopies: false,
    // 打印价格
    printFee: 0.00,
    totalFee: 0.00,
    // 配送价格
    deliveryFee: 0.00,
    pickUpId: "",
    payment_success: false,
    page_sy: "",
    sc_type: false
  },
  onLoad: function (options) {
    let pages = getCurrentPages();
    let prevpage = pages[pages.length - 2];
    this.data.page_sy = prevpage.route;
    if (options) {
      if (options.type == "sc") {
        this.s_set(options.fileId);
      }
    }
    this.getPrintLists();
  },
  onRefresh: function () {
    //导航条加载动画
    wx.showNavigationBarLoading();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      //停止下拉刷新
      wx.stopPullDownRefresh();
    }, 2000);
  },
  onShow: function () {
    if (!app.globalData.isLogin) {
      wx.reLaunch({
        url: '/pages/wode/index',
      })
      return;
    }
    //跳转到网页上传文件，返回时自动关闭
    this.setData({
      hideAdd: true
    });
    let printer = app.globalData.printer;
    if (printer == undefined) {
      wx.showModal({
        title: "提示",
        content: "请先选择打印机",
        showCancel: false,
        confirmText: "去选择",
        success: res2 => {
          if (res2.confirm) {
            wx.navigateTo({
              url: '../shop/index',
            })
          }
        }
      })
    } else {
      this.setData({
        printer_name: `${app.globalData.printer.printerName}(${app.globalData.printer.shopName})`,
        printer: app.globalData.printer,
        payment_success: false
      })
    }
    this.getPrintLists();
  },
  onHide() {

  },
  getTotalFee() {
    if (typeof this.data.printer !== "undefined") {
      let queueIds = [];
      this.data.queueLists.forEach((item, index) => {
        queueIds.push(item.id);
      })
      let data = {
        printerId: this.data.printer.id,
        pickUpId: this.data.pickUpId,
        deliveryType: this.data.deliveryType,
        queueIdList: queueIds
      }
      getTotalFeeByService(data).then(res => {
        if (res.code == 200) {
          this.setData({
            totalFee: res.data.totalFeeOfYuan,
            printFee: res.data.printFeeOfYuan,
            deliveryFee: res.data.deliveryFeeOfYuan,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            mask: true,
          })
        }
      }).catch(err => {
        wx.hideLoading();
        console.log("获取价格失败", err);
      })
    }
  },
  //获取打印列表
  getPrintLists(callback = null) {
    getQueueList().then(res => {
      if (res.code == 200) {
        this.setData({
          queueLists: res.data
        });
        this.getTotalFee();
      }
    })
  },
  preview(e) {
    if (fileId <= 0) {
      return
    }
    let fileId = e.currentTarget.dataset.index;
    wx.showLoading({
      title: '正在打开...',
      mask: true,
    })

    let ext = ""
    let data = {
      fileId: fileId
    }
    getPrintFileInfo(data).then(res => {
      if (res.code == 200) {
        console.log("预览", res)
        ext = res.data.fileExt
      }
      let fileListTmp = wx.getStorageSync('fileListTmp');
      if (fileListTmp && fileListTmp[fileId]) {
        wx.hideLoading();
        try {
          // 文件存在
          fs.accessSync(fileListTmp[fileId])
          console.log("读取缓存", fileId)
          this.openFile(ext, fileListTmp[fileId])
        } catch (e) {
          console.log("读取服务器", fileId)
          // 文件不存在
          this.downloadForServer(ext, res.data.fileUrl, fileId);
        }
      } else {
        console.log("读取服务器", fileId)
        this.downloadForServer(ext, res.data.fileUrl, fileId);
      }
    }).catch(err => {
      console.log("获取文件信息报错", err)
    })

  },
  downloadForServer(ext, fileUrl, fileId) {
    wx.downloadFile({
      url: fileUrl,
      success: res => {
        wx.hideLoading();
        //设置缓存
        let fileListTmp = wx.getStorageSync('fileListTmp')
        if (!wx.getStorageSync('fileListTmp')) {
          fileListTmp = new Object();
        }
        fileListTmp[fileId] = res.tempFilePath
        wx.removeStorageSync('fileListTmp');
        wx.setStorageSync('fileListTmp', fileListTmp);
        this.openFile(ext, res.tempFilePath)
      },
      fail: err => {
        wx.hideLoading();
        err = JSON.stringify(err);
        wx.showModal({
          title: "警告",
          content: "预览错误",
          confirmText: "复制错误",
          success: _ => {
            if (_.confirm) {
              wx.setClipboardData({
                data: err,
              })
            }
          }
        })
      }
    })
  },
  openFile(ext, path) {
    switch (ext) {
      case "doc":
      case "docx":
      case "xls":
      case "xlsx":
      case "ppt":
      case "pptx":
      case "pdf":
        wx.openDocument({
          filePath: path,
          fileType: ext,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: (res) => {
            console.log('打开文档失败', res)
          }
        })
        break;
      case "jpg":
      case "png":
      case "jpeg":
        wx.previewImage({
          urls: [path],
          current: path
        })
        break;
      default:
        wx.showToast({
          title: '文件类型不支持预览',
          icon: 'error',
          mask: true,
        })
    }
  },
  deleteFile: function (e) {
    let queueId = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "确定要删除吗?",
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '正在删除',
          })
          let data = {
            id: queueId
          }
          deleteQueueById(data).then(res => {
            wx.hideLoading();
            wx.showToast({
              title: res.data,
              icon: "none",
              mask: true,
              duration: 200,
            })
            if (res.code === 200) {
              this.getPrintLists();
            };
          }).catch(err => {
            console.log("删除文件报错", err)
          })
        }
      }
    })
  },
  update_set(e) {
    let fileId = e.currentTarget.dataset.id;
    this.s_set(fileId)
  },
  /**
   * 文件上传后显示的设置页面
   * @param {*} fileId 
   */
  s_set(fileId) {
    let data = {
      fileId: fileId
    }
    getPrintFileInfo(data).then(res => {
      if (res.code == 200) {
        this.handleFile(res.data)
      }
    }).catch(err => {
      console.log("获取文件信息报错", err)
    })
  },
  handleFile(fileInfo) {
    let _that = this
    let queueLists = this.data.queueLists;
    let setting = undefined;
    if (queueLists !== undefined) {
      let queue;
      queueLists.forEach((item, index) => {
        if (item.fileId === fileInfo.id) {
          queue = queueLists[index];
          setting = {
            "fileId": fileInfo.id,
            "queueId": queue.id,
            "side": queue.side,
            "color": queue.color,
            "copies": queue.copies,
            "orientation": queue.orientation,
            'isPageRange': queue.isPageRange,
            "pageStart": queue.pageStart,
            "pageEnd": queue.pageEnd
          }
          return;
        }
      })
    }
    if (setting == undefined) {
      setting = {
        "fileId": fileInfo.id,
        "side": 1,
        "color": 1,
        "copies": 1,
        "orientation": 1,
        "pageStart": 1,
        'isPageRange': 1,
        "pageEnd": fileInfo.filePagNum
      }
    }
    let hidePages = true;
    if (setting.isPageRange == 2) {
      hidePages = false
    }
    if (fileInfo.originalFileName == "身份证") {
      _that.setData({
        setting: setting,
        hideSetting: false,
        hideSides: true,
        hideColor: true,
        hideOrientation: true,
        hideIsPageRange: true,
        hidePages: hidePages,
        hideCopies: false,
      })
    } else if (fileInfo.originalFileName == "拍照扫描.jpg") {
      _that.setData({
        setting: setting,
        hideSetting: false,
        hideSides: true,
        hideColor: false,
        hideOrientation: true,
        hideIsPageRange: true,
        hidePages: hidePages,
        hideCopies: false,
      })
    } else if (fileInfo.fileExt === "jpeg" || fileInfo.fileExt === "jpg" || fileInfo.fileExt === "png") {
      _that.setData({
        setting: setting,
        hideSetting: false,
        hideSides: true,
        hideColor: false,
        hideOrientation: false,
        hideIsPageRange: true,
        hidePages: hidePages,
        hideCopies: false,
      })
    } else {
      _that.makePagePicker(fileInfo);
      _that.setData({
        setting: setting,
        hideSetting: false,
        hideSides: false,
        hideColor: false,
        hideOrientation: false,
        hideIsPageRange: false,
        hidePages: hidePages,
        hideCopies: false,
      })
    }
  },
  close() {
    this.setData({
      hideSetting: true,
    })
  },
  //页码选择
  makePagePicker(fileInfo, _that) {
    let pages = fileInfo.filePagNum;
    let pagesPicker = [];
    if (pages > 1) {
      let start = [];
      let end = [];
      for (let i = 1; i <= pages; i++) {
        start.push(i);
      }
      for (let i = pages; i >= 1; i--) {
        end.push(i);
      }
      pagesPicker = [start, end];
    } else {
      pagesPicker = [
        [1],
        [1]
      ];
    }
    this.setData({
      pagesPicker: pagesPicker
    });
  },
  //单双面设置
  settingSide(e) {
    let side = e.currentTarget.dataset.side;
    if (side == 2 && !this.data.printer.supportFunctions.includes("双面打印")) {
      wx.showToast({
        title: '不可使用双面',
        icon: 'error',
        duration: 2000
      })
      return false;
    }
    let setting = this.data.setting;
    setting.side = side;
    this.setData({
      setting: setting
    })
  },
  //黑白设置
  settingColor(e) {
    let color = e.currentTarget.dataset.color;
    if (color == 1 && !this.data.printer.supportFunctions.includes("黑白打印")) {
      wx.showToast({
        title: '不可使用黑白',
        icon: 'error',
        duration: 2000
      })
      return false;
    }
    if (color == 2 && !this.data.printer.supportFunctions.includes("彩色打印")) {
      wx.showToast({
        title: '不可使用彩印',
        icon: 'error',
        duration: 2000
      })
      return false;
    }

    let setting = this.data.setting;
    setting.color = color;
    this.setData({
      setting: setting
    })
  },
  //打印方向
  settingOrientation(e) {
    let orientation = e.currentTarget.dataset.orientation;
    let setting = this.data.setting;
    setting.orientation = orientation;
    this.setData({
      setting: setting
    })
  },
  //页面范围
  bindPagesPickerColumnChange(e) {
    let pagesPicker = this.data.pagesPicker;
    let page_count = pagesPicker[0].length;
    let value = e.detail.value;
    let column1 = [];
    if (e.detail.column === 0) {
      for (let i = 1; i <= (page_count - value); i++) {
        column1.push(i + value);
      }
      pagesPicker[1] = column1;
      this.setData({
        pagesPicker: pagesPicker
      })
    }
  },
  bindPagesPickerChange(e) {
    let setting = this.data.setting;
    let pagesPicker = this.data.pagesPicker;
    setting.pageStart = pagesPicker[0][e.detail.value[0]];
    setting.pageEnd = pagesPicker[1][e.detail.value[1]];
    this.setData({
      setting: setting
    })
  },
  settingIsPageRange(e) {
    let isPageRange = e.currentTarget.dataset.ispagerange;
    let setting = this.data.setting;
    setting.isPageRange = isPageRange;
    if (isPageRange == 2) {
      this.setData({
        hidePages: false
      })
    } else {
      this.setData({
        hidePages: true
      })
    }
    this.setData({
      setting: setting
    })
  },
  //打印份数
  settingCopies(e) {
    let setting = this.data.setting;
    let copies = setting.copies;
    let field = e.currentTarget.dataset.field;
    if (field === "subtract") {
      copies = copies - 1 > 0 ? copies - 1 : 1;
    } else {
      copies += 1;
    }

    setting.copies = copies;
    this.setData({
      setting: setting
    })
  },
  confirmSetting() {
    let setting = this.data.setting;
    let queueLists = this.data.queueLists;
    if (queueLists == undefined) {
      queueLists = []
    } else {
      queueLists.forEach((item, index) => {
        if (item.fileId === setting.fileId) {
          queueLists[index] = setting;
        }
      })
    }
    wx.showLoading({
      title: '正在设置...',
      mask: true,
    })
    saveOrUpdatePrint(setting).then(res => {
      console.log(setting)
      wx.showToast({
        title: "设置成功",
        mask: true,
        duration: 100,
      })
      this.setData({
        setting: null,
        hideSetting: true,
      })
      //更新打印列表
      this.getPrintLists();
    }).catch(err => {

    })
  },
  //显示添加文件窗口
  addFile() {
    this.setData({
      hideAdd: false
    })
  },
  //关闭添加文件窗口
  closeAddFile() {
    this.setData({
      hideAdd: true
    })
  },
  selectFile: function (e) {
    this.closeAddFile();
    let type = e.currentTarget.dataset.type;
    wx.chooseMessageFile({
      count: 1,
      type: type,
      extension: ["doc", "xls", "xlsx", "docx", "ppt", "pptx", "pdf"],
      success: res => {
        for (let i = 0; i < res.tempFiles.length; i++) {
          let file = {
            path: res.tempFiles[i]["path"],
            filename: res.tempFiles[i]["name"]
          };
          app.upload(file, this.data.printer.id).then(res => {
            // 回传文件ID
            this.s_set(res.data.id);
            let fileListTmp = wx.getStorageSync('fileListTmp')
            if (!wx.getStorageSync('fileListTmp')) {
              fileListTmp = new Object();
            }
            fileListTmp[res.data.id] = file.path
            wx.removeStorageSync('fileListTmp');
            wx.setStorageSync('fileListTmp', fileListTmp);
          }, err => {
            wx.hideLoading();
            wx.showModal({
              title: "提示",
              content: err.msg
            })
          })
        }
      }
    })
  },
  onPullDownRefresh() {
    this.getPrintLists(_ => {
      wx.stopPullDownRefresh({
        success: (res) => {
          wx.showToast({
            title: '已刷新',
            icon: "none",
            mask: true
          })
        },
        fail: (res) => { },
        complete: (res) => { },
      })
    });
  },
  editPhoto(e) {
    let index = e.currentTarget.dataset.index;
    let photo_data = this.data.queueLists[index];
    let data = {
      path: photo_data.file,
      size: "photo",
      process: "Photoedit",
      printer_id: photo_data.id,
    };
    wx.setStorage({
      data: data,
      key: 'takePhoto',
      success: _ => {
        wx.navigateTo({
          url: '../photo_resize/index',
        })
      }
    })
  },
  submitDeliveryOrder() {
    console.log(11111111, this.data.deliveryType)
    if (this.data.deliveryType !== 1 && this.data.deliveryType !== 0 && this.data.deliveryType !== 999) {
      wx.showToast({
        title: "请选择配货方式",
        icon: 'error',
        duration: 1000
      })
      return;
    }
    if (this.data.deliveryType == 1 || this.data.deliveryType == 0) {
      console.log("联系人", this.data.deliveryContact)
      console.log("联系号码", this.data.deliveryPhone)
      console.log("联系地址", this.data.deliveryAddress)

      if (this.data.deliveryContact == '') {
        wx.showToast({
          title: '联系人未填',
          icon: 'error'
        })
        return
      } else if (this.data.deliveryPhone == '') {
        wx.showToast({
          title: '联系号码未填',
          icon: 'error'
        })
        return
      } else if (this.data.deliveryAddress == '' || this.data.deliveryAddress == '请选择送货地址' || this.data.deliveryAddress == '请选择签收点') {
        wx.showToast({
          title: '地址为空',
          icon: 'error'
        })
        return
      }
    }
    this.setData({
      hideDelivery: true
    })
    this.payment();
  },
  payment() {
    wx.showModal({
      title: "提示",
      content: `您已经选择了【${this.data.printer.printerName}】打印机,支付后将立即打印!`,
      success: res => {
        if (res.confirm) {
          let queueIds = [];
          this.data.queueLists.forEach((item, index) => {
            queueIds.push(item.id);
          })
          let printerId = this.data.printer.id;
          let data = {
            printerId: printerId,
            queueIdList: queueIds,
            deliveryAddress: this.data.deliveryAddress,
            deliveryPhone: this.data.deliveryPhone,
            deliveryContact: this.data.deliveryContact,
            pickUpId: this.data.pickUpId,
            deliveryType: this.data.deliveryType
          }
          console.log("发起支付参数", data)
          wx.showLoading({
            title: '调起支付中...',
            mask: true,
          })
          createPrintOrder(data).then(res => {
            wx.hideLoading();
            if (res.code != 200) {
              wx.showToast({
                title: res.msg,
                icon: 'error',
                mask: true,
                duration: 3000
              })
              return;
            }
            let orderId = res.data.orderId;
            // 如果是免费的
            if (!res.data.orderV3) {
              this.setData({
                payment_success: true,
              })
              wx.showToast({
                title: '支付成功',
                mask: true,
              })
              setTimeout(_ => {
                wx.redirectTo({
                  url: '/pages/printing/index?orderId=' + orderId,
                })
              }, 500)
            } else {
              res.data.orderV3.package = res.data.orderV3.packageValue
              if (res.code == 200) {
                //调起支付
                console.log("调起支付", res.data.orderV3);
                wx.requestPayment(Object.assign(res.data.orderV3, {
                  success: res => {
                    let queryPay = {
                      "orderId": orderId
                    }
                    queryPayResult(queryPay).then(res => {
                      console.log("支付状态", res);
                      if (res.code == 200) {
                        this.setData({
                          payment_success: true,
                        })
                        wx.showToast({
                          title: '支付成功',
                          mask: true,
                        })
                        setTimeout(_ => {
                          wx.redirectTo({
                            url: '/pages/printing/index?orderId=' + orderId,
                          })
                        }, 500)
                      }
                    })
                  },
                  fail: err => {
                    console.log("ERR", err)
                    wx.showModal({
                      title: '支付失败',
                      content: '请去我的>我的订单里查看',
                      confirmText: '前去查看',
                      success(res) {
                        if (res.confirm) {
                          wx.reLaunch({
                            url: '/pages/or_list/index',
                          })
                        } else if (res.cancel) {
                          getPrintLists();
                          console.log('刷新队列')
                        }
                      }
                    })
                  }
                }))
              }
            }
          })
        }
      }
    })
  },
  // 送货窗口
  setDelivery() {
    if (this.data.printer === undefined) {
      wx.showModal({
        content: "未选择打印机",
        confirmText: "去选择",
        success: res => {
          if (res.confirm) {
            wx.navigateTo({
              url: '../shop/index',
            })
          }
        }
      })
      return;
    }
    this.setData({
      hideDelivery: false,
      deliveryFee: "0.00",
      totalFee: this.data.printFee,
      deliveryType: -1,
      deliveryFee: "0.00",
      deliveryAddress: "",
      deliveryContact: "",
      deliveryPhone: ""
    })
    const selectDelivery = this.selectComponent('#selectDelivery');
    selectDelivery.handleReset();
  },
  closeSetDelivery() {
    this.setData({
      hideDelivery: true,
      deliveryType: -1
    })
    const selectDelivery = this.selectComponent('#selectDelivery');
    selectDelivery.handleReset();
  },
  bindDeliveryChange: function (e) {
    this.setData({
      delivery: {
        ...e.detail
      },
      deliveryFee: "0.00",
      totalFee: this.data.printFee,
      deliveryType: 999,
      deliveryFee: "0.00",
      deliveryAddress: "",
      deliveryContact: "",
      deliveryPhone: ""
    })

    if (this.data.delivery.id == '001') {
      this.setData({
        deliveryType: 0,
        deliveryAddress: "请选择送货地址"
      })
    }
    if (this.data.delivery.id == '002') {
      this.setData({
        deliveryType: 1,
        deliveryAddress: "请选择签收点"
      })
    }
    if (this.data.delivery.id == '999') {
      this.getTotalFee()
    }
  },
  //选择签收点
  goPickup: function (e) {
    wx.navigateTo({
      url: './pickup',
    })
  },
  goUserAddress: function (e) {
    wx.navigateTo({
      url: '/pages/wode/address_list',
    })
  },
  bindKeyInput(e) {
    this.setData({
      [`${e.currentTarget.dataset.params}`]: e.detail.value
    })
  },
  navigatorToShop(e) {
    console.log(printer);
    let printer = this.data.printer;
    if (printer == undefined) {
      console.log("未设置默认打印点")
      return
    }
    wx.showModal({
      title: "提示",
      content: "确认导航到打印点？",
      cancelText: "取消",
      confirmText: "去导航",
      success: res => {
        if (res.confirm) {
          let lat = parseFloat(printer.lat);
          let lng = parseFloat(printer.lng);
          wx.openLocation({
            latitude: lat,
            longitude: lng,
          })
        }
      }
    })
  },
})